// pages/product/index.js
import { Product } from '../product/product-model.js';
import {Cart} from '../cart/cart-model.js';
var product = new Product();
var cart = new Cart();
Page({

  /**
   * 页面的初始数据
   */
  data: {
      id:'', 
      product:'',
      countArr:[1,2,3,4,5,6],
      productCount:1,  //默认显示的数量
      detailTitle:['商品详情','产品参数','售后保障'],
      chooseIndex:''//默认选中的标题下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var that = this;
      var id = options.id;
      that.setData({
         id:id
      })

      that.loadData();
  },
  //获取商品详情
  loadData:function(){
      var that = this;
      var id = that.data.id;
      product.getDetailInfo(id,(res)=>{
        that.setData({
           //初始化购物车商品数量
           carTotalCounts:cart.getCartTotalCounts(),
           product:res
        })
      })
  },

  //picker绑定参数,选择数量
  bindPickerChange:function(e){
      var that = this;
      var index = e.detail.value;
      var selectedtCount = that.data.countArr[index];
      that.setData({
        productCount: selectedtCount
      })
  },

  //绑定选中的标题
  onTabsItem:function(e){
     var that = this;
     var index = that.getEvenData(e,'index');
     that.setData({
       chooseIndex:index
     })
  },
  

  //添加购物车
  onAddCartTap:function(e){
     //增加购物车
     this.addToCart();
     //更新购物车中的商品数量: 原有数量 + 最新增加的数量
     var counts = this.data.productCount + this.data.carTotalCounts;
     this.setData({
       carTotalCounts: counts
     })
  },



  //获取商品数据(购买的是哪一个商品):商品详情页面，所以你能选择的商品就只能是该页面展示的商品
  addToCart:function(){
      var tempObj = {};//存放选中的商品的数据
      var keys = ['id','name','main_img_url','price'];

      for(var key in this.data.product){
          if(keys.indexOf(key)!=-1){
              tempObj[key] = this.data.product[key];
          }
      }

     cart.addCart(tempObj, this.data.productCount);
  },

  //点击调转到购物车页面
  onCart:function(e){
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },

  getEvenData: function (e, key) {
    return e.currentTarget.dataset[key];
  }




})